package com.gss.module.translate.chromedriver;

import com.gss.module.translate.Translation;
import com.gss.module.translate.constants.ConstantsUrl;
import com.gss.module.translate.constants.TransType;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

/**
 * @author DYang
 * @date 2023/6/8
 * 微软翻译，使用chromedriver实现
 */
public class BingTranslator extends AbstractChromeDriver{

    public final String TRANS_NAME = TransType.BING_TRANS.TRANS;

    protected WebDriver webDriver;
    protected Translation instance;

    @Override
    public Translation getInstance() {
        if (webDriver == null) {
            webDriver = this.buildChromeDriver();
            webDriver.get(ConstantsUrl.BING_TRANS);
            instance = this;
        }
        return instance;
    }

    @Override
    public void inputText(String input, long timeout) {
        WebElement inputBox = webDriver.findElement(By.id("tta_input_ta"));
        if (inputBox == null){
            return;
        }
        inputBox.clear();
        inputBox.sendKeys(input);
        inputBox.sendKeys("");
        //留给足够的时间执行
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getTransOut() {
        WebElement translationResult = webDriver.findElement(By.id("tta_output_ta"));
        return translationResult != null ? translationResult.getText() : null;
    }

    @Override
    public void closeTrans() {
        if (webDriver != null) {
            webDriver.quit();
            webDriver = null;
        }
        instance = null;
    }
}
